package com.sxbbc.common.core.service.system.pay;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.mode.ModeService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxbbc.common.basics.enums.ServiceEnums;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;

/**
 * 订单回调业务层
 *
 * @author arno
 */
@Service
public class OrderBackService {

    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private IChickenLevelService iChickenLevelService;
    @Autowired
    private IChickenOrderService iChickenOrderService;
    @Autowired
    private IOrderMainService iOrderMainService;
    @Autowired
    private IOrderDetailService iOrderDetailService;
    @Autowired
    private IProSkuDetailService iProSkuDetailService;
    @Autowired
    private IBOfflineService ibOfflineService;
    @Autowired
    private IChickenCouponService iChickenCouponService;
    @Autowired
    private IAccountChangeService iAccountChangeService;
    @Autowired
    private ModeService modeService;

    /**
     * 处理订单回调（有模式）
     *
     * @param cPayLog
     */
    public void handleOrderCallBack(CPayLog cPayLog) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //1.修改订单状态 查询订单信息
        QueryWrapper<OrderMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pay_code", cPayLog.getPayCode());
        queryWrapper.eq("order_status", OrderStatusEnums.COMFIRE.getId());
        List<OrderMain> list = iOrderMainService.list(queryWrapper);
        if (list == null || list.size() < 1) {
            throw new ThrowJsonException("订单已被处理");
        }

        //根据统一下单支付业务类型 获取对应的 资金金明细类型
        ServiceEnums enums = ServiceEnums.getEnums(cPayLog.getServiceType());
        Integer handleType = HandleTypeEnums.BUY.getId();

        for (OrderMain l : list) {
            //更新订单状态
            l.setTransCode(cPayLog.getTransCode());
            if (calUtil.isEquals(cPayLog.getServiceType(), ServiceEnums.ORDER.getId())) {
                l.setOrderStatus(OrderStatusEnums.NEED_SEND.getId());
            } else if (calUtil.isEquals(cPayLog.getServiceType(), ServiceEnums.OFFLINE_ORDER.getId())) {
                l.setOrderStatus(OfflineOrderStatusEnums.WAIT_USED.getId());
            }

            l.setPayTime(DateUtil.getInstance().currentDate());
            iOrderMainService.updateById(l);
            List<OrderDetail> details = iOrderDetailService.listByOrderCode(l.getOrderCode());
            for (OrderDetail d : details) {
                //增加销售库存 无需根据版本号
                ProSkuDetail detail = new ProSkuDetail();
                detail.setId(d.getProDetailId());
                detail.setQty(d.getQty());
                iProSkuDetailService.updateSaleqty(detail);

                //1、赠送积分（创业分）
                if (d.getPoint() != null && BigDecimal.ZERO.compareTo(d.getPoint()) < 0) {
                    BigDecimal totalPoint = calUtil.mul(d.getPoint(), new BigDecimal(d.getQty()), 2);
                    String msg = iAccountChangeService.insertCPointDetail(cPayLog.getCid(), handleType, StaticUtils.PAY_IN,
                            cPayLog.getPayCode(), totalPoint, HandleTypeEnums.getName(handleType), cPayLog.getCid());
                    if (!StringUtils.isEmpty(msg)) {
                        throw new ThrowJsonException(msg);
                    }
                }
            }
            //模式处理
            modeService.modeMain(details, l.getCid(), l.getPayCode(), l.getBid(), null, cPayLog.getServiceType());
        }
    }

    /**
     * 处理物流提鸡订单回调（无模式）
     *
     * @param cPayLog
     */
    public void handleFarmLogisticsOrderCallBack(CPayLog cPayLog) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //1.修改订单状态 查询订单信息
        QueryWrapper<OrderMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pay_code", cPayLog.getPayCode());
        queryWrapper.eq("order_status", OrderStatusEnums.COMFIRE.getId());
        List<OrderMain> list = iOrderMainService.list(queryWrapper);
        if (list == null || list.size() < 1) {
            throw new ThrowJsonException("订单已被处理");
        }
        for (OrderMain l : list) {
            //更新订单状态
            l.setTransCode(cPayLog.getTransCode());
            if (calUtil.isEquals(cPayLog.getServiceType(), ServiceEnums.FARM_LOGISTICS_ORDER.getId())) {
                l.setOrderStatus(OrderStatusEnums.NEED_SEND.getId());
            }
            l.setPayTime(DateUtil.getInstance().currentDate());
            iOrderMainService.updateById(l);

            ChickenCoupon chickenCoupon = iChickenCouponService.getById(l.getCouponId());
            if (CalcuUtils.getInstance().isEquals(chickenCoupon.getStatus(), ChickenCouponStatusEnums.WAITUSE.getId())) {
                chickenCoupon.setStatus(ChickenCouponStatusEnums.USED.getId());
                chickenCoupon.setUseTime(new Date());
            }
            iChickenCouponService.updateById(chickenCoupon);
        }
    }

    /**
     * 处理农场养鸡订单回调 (有模式)
     *
     * @param cPayLog
     */
    public void handleFarmOrderCallBack(CPayLog cPayLog) {

        CalcuUtils calUtil = CalcuUtils.getInstance();
        //1.修改订单状态 查询订单信息
        QueryWrapper<ChickenOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pay_code", cPayLog.getPayCode());
        queryWrapper.eq("order_status", FarmOrderStatusEnums.COMFIRE.getId());
        ChickenOrder order = iChickenOrderService.getOne(queryWrapper);
        if (order == null) {
            throw new ThrowJsonException("订单已被处理");
        }
        //更新订单状态
        order.setTransCode(cPayLog.getTransCode());
        if (calUtil.isEquals(cPayLog.getServiceType(), ServiceEnums.FARM_ORDER.getId())) {
            order.setOrderStatus(FarmOrderStatusEnums.WAIT.getId());
        }
        order.setPayTime(new Date());
        iChickenOrderService.updateById(order);

        //加销售库存
        ChickenLevel chickenLevel = iChickenLevelService.getById(order.getCrId());
        int qty = order.getBuyNum() / chickenLevel.getQty();
        chickenLevel.setSaleQty(chickenLevel.getSaleQty() + qty);
        iChickenLevelService.updateById(chickenLevel);

        //扣除积分（创业分）
        if (cPayLog.getPoint() != null && BigDecimal.ZERO.compareTo(cPayLog.getPoint()) < 0) {
            String msg = iAccountChangeService.insertCPointDetail(cPayLog.getCid(), HandleTypeEnums.FARM_BUY.getId(), StaticUtils.PAY_OUT,
                    cPayLog.getPayCode(), cPayLog.getPoint(), HandleTypeEnums.getName(HandleTypeEnums.FARM_BUY.getId()), cPayLog.getCid());
            if (!StringUtils.isEmpty(msg)) {
                throw new ThrowJsonException(msg);
            }
        }

        //生成订单预分红记录 根据分红频率生成待解冻提鸡券和待解冻基金
        //modeService.addChickenCouponList(order);
        modeService.generateFarmBonusRecordByBonusDay(order);
    }

    /**
     * 处理线下买单订单回调
     *
     * @param cPayLog
     */
    public void handleOfflineBuyOrderCallBack(CPayLog cPayLog) {

        CalcuUtils calUtil = CalcuUtils.getInstance();

        QueryWrapper<BOffline> offlineWrapper = new QueryWrapper<>();
        offlineWrapper.eq("pay_code", cPayLog.getPayCode());
        BOffline offline = ibOfflineService.getOne(offlineWrapper);
        if (offline == null || calUtil.isEquals(StaticUtils.STATUS_YES, offline.getStatus())) {
            throw new ThrowJsonException("交易不存在或已处理");
        }
        offline.setStatus(StaticUtils.STATUS_YES);
        offline.setEndTime(new Date());
        ibOfflineService.updateById(offline);

        //赠送积分（创业分）
        if (cPayLog.getPoint() != null && BigDecimal.ZERO.compareTo(cPayLog.getPoint()) < 0) {
            String msg = iAccountChangeService.insertCPointDetail(cPayLog.getCid(), HandleTypeEnums.OFFLINE_BUY.getId(), StaticUtils.PAY_IN,
                    cPayLog.getPayCode(), cPayLog.getPoint(), HandleTypeEnums.getName(HandleTypeEnums.OFFLINE_BUY.getId()), cPayLog.getCid());
            if (!StringUtils.isEmpty(msg)) {
                throw new ThrowJsonException(msg);
            }
        }
        //模式处理
        modeService.modeMain(null, offline.getCid(), cPayLog.getPayCode(), offline.getBid(), offline, ServiceEnums.OFFLINE_BUY.getId());
    }
}
